"""
依赖注入模块
"""
from app.core.database import SessionLocal
from sqlalchemy.orm import Session
from fastapi import HTTPException, status
import logging

logger = logging.getLogger(__name__)

def get_db() -> Session:
    """获取数据库会话"""
    db = SessionLocal()
    try:
        yield db
    except Exception as e:
        if isinstance(e, HTTPException):
            raise e
        
        # 只捕获与数据库连接相关的异常
        if "connection" in str(e).lower() or "timeout" in str(e).lower() or "pool" in str(e).lower():
            logger.error(f"数据库连接异常: {str(e)}")
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                detail="数据库连接异常"
            )
        # 对于其他异常，直接向上抛出
        raise
    finally:
        db.close()